/**
 * Created by Administrator on 2015/12/1.
 */

var express = require('express');
var router = express.Router();
//var articleService = require('../service/articleService')
var service = require('../service/service');
var Tool = require('../service/tool');

//        var article = {
//            _id:'246543165464654',
//            title:'这个是个问题',
//            body:'苴侯求救于秦，蜀王杜芦也派使者与秦结盟，目的是不希望秦干涉苴政。但狡诈的秦惠王嬴驷收了二国的礼物后，派张仪、张若、司马错率队走石牛道（今剑阁金牛道/剑阁道）灭蜀吞苴，蜀王身死，苴侯被废，蜀太子逃到彭乡（今彭州）被捉。《本蜀论》记载惠文王用计灭古蜀：“秦惠王欲伐蜀而不知道(路)，作五石牛，以金置尾下，言能屎金，蜀王负力，令五丁引之，成(蜀)道。秦使张仪、司马错寻路灭蜀，因曰石牛道。”秦惠王任蜀太子为蜀侯，张若为蜀相，置蜀郡。宣告蜀、苴二国灭亡。',
//            user:{
//                _id:'56465432131654',
//                username:'dongge'
//            },
//            date:'2015-12-5'
//        }
/**
 * data structure
 * {
         *  total:x,
         *  articles:[
         *      {
         *          _id:
         *          title:
         *          body:
         *          user:{
         *              _id:
         *              username:
         *          }
         *          date:
         *      }
         *  ]
         * }
 */
router.use(function(req,res,next){
    console.log('article is called');
    var url = req.path;
    var allowedUrls = ['/list','/listbyuser','/get'];
    var allowed = false;
    if(!req.session.user){//没有登录的用户是可以访问list或者用户的的article list
        for(var i = 0;i<allowedUrls.length;i++){
            var r = new RegExp("^"+allowedUrls[i]+"$");
            if(r.test(url)){
                allowed = true;
                break;
            }
        }
    }else {
        allowed = true;
    }
    if(!allowed){
        res.redirect('/refuse.html');
    }else{
        next();
    }
    /**
     * 权限控制 没有登录的用户不能发表和修改文章，但是可以浏览文章。
     */
});
router.get('/list',function(req,res){
    service.getArticles(req.query.page,function(retMsg){
        if(retMsg.state){
            res.render('article/list',retMsg);
        }else{
            res.render('article/error',retMsg);
        }
    })
});

router.get('/listbyuser',function(req,res){
    service.getArticlesByUser(req.query.id,req.query.page,function(retMsg){
        if(retMsg.state){
            res.render('article/list',retMsg);
        }else{
            res.render('article/error',retMsg);
        }
    })
});

router.get('/get',function(req,res){
    service.getArticle(req.query.id,function(retMsg){
        if(retMsg.state){
            var article = retMsg.article;
            article.comments = Tool.commentsFormat(retMsg.comments);
            res.render('article/detail',article);
        }else{
            res.render('article/error',retMsg);
        }
    })
});

router.get('/addform',function(req,res){
    res.render('article/addform.html');
});

router.post('/add',function(req,res){
    var a = req.body;
    a.userId = req.session.user._id;
    service.addArticle(a,function(retMsg){
        if(retMsg.state){
            res.redirect('/article/get?id='+retMsg.article.id);
        }else{
            res.render('article/error',retMsg);
        }

    })
});

router.get('/remove',function(req,res){
    service.getArticle(req.query.id,function(ret){
        if(ret.state){
            if(req.session.user.id == ret.article.userId){//只有拥有该文件的用户才能删除它
                service.removeArticle(req.query.id,function(retMsg){
                    if(retMsg.state){
                        res.render('article/success',retMsg);
                    }else{
                        res.render('article/error',retMsg);
                    }
                })
            }else{
                ret.state = 0;
                ret.message = '你没有删除该文件的权限';
                res.render('article/error',ret);
            }
        }else{
            //ret.state = 0;
            //ret.message = '没有找到你要删除的文件';
            res.render('article/error',ret);
        }
    })

});

router.get('/editform',function(req,res){
    service.getArticle(req.query.id,function(ret){
        if(ret.state){
            if(req.session.user.id == ret.article.userId){//只有拥有该文件的用户才能编辑它
                //service.getArticle(req.query.id,function(retMsg){
                //    if(retMsg.state){
                //        res.render('article/editform',retMsg.article);
                //    }else {
                //        res.render('article/error',retMsg);
                //    }
                //})
                res.render('article/editform',ret.article);
            }else{
                ret.state = 0;
                ret.message = '你没有编辑该文件的权限';
                res.render('article/error',ret);
            }
        }else{
            //ret.state = 0;
            //ret.message = '没有找到你要删除的文件';
            res.render('article/error',ret);
        }
    })

});

router.post('/edit',function(req,res){

    service.getArticle(req.query.id,function(ret){
        if(ret.state){
            if(req.session.user.id == ret.article.userId){//只有拥有该文件的用户才能编辑它
                service.editArticle(req.body,function(retMsg){
                    if(retMsg.state){
                        res.render('article/detail',retMsg.article);
                    }else {
                        res.render('article/error',retMsg);
                    }

                })
            }else{
                ret.state = 0;
                ret.message = '你没有编辑该文件的权限';
                res.render('article/error',ret);
            }
        }else{
            //ret.state = 0;
            //ret.message = '没有找到你要删除的文件';
            res.render('article/error',ret);
        }
    })
});



//router.all('/list',function(req,res,next){
//    console.log('list is call');
//    console.log(req.query.page);
//    articleService.getArticleList(req.query.page,function(data){
//        res.json(data);
//    })
//});
//router.all('/detail',function(req,res,next){
//    //articleService.getArticle(req.query.id,function(data){
//    //
//    //})
////    res.render('Hello',{message:'dongge'});
//    //res.send('hello');
//    console.log(req.query.id);
//    articleService.getArticle(req.query.id,function(data){
//        console.log(data);
//        res.render('detail',data);
//    });
//
//});

module.exports = router;
